import requestsimport json
from bs4 import BeautifulSoup
from urllib import parse

import os# 文章地址获取

def main():    
    path_url = input("请输入链接地址：")    
    if not path_url:        
        print("请在下方输入链接地址")        
        path_url = input("地址：")    
        return path_url# 视频地址解析def analysis(url):    
        # 获取响应码    

    res = requests.get(url)    
    code = res.status_code    
if code != 200:        
    print('无法响应')    # 获取页面代码    
    headers = {        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36",        "Cookie": "anonymid=j3jxk555-nrn0wh; _r01_=1; _ga=GA1.2.1274811859.1497951251; _de=BF09EE3A28DED52E6B65F6A4705D973F1383380866D39FF5; ln_uact=mr_mao_hacker@163.com; depovince=BJ; jebecookies=54f5d0fd-9299-4bb4-801c-eefa4fd3012b|||||; JSESSIONID=abcI6TfWH4N4t_aWJnvdw; ick_login=4be198ce-1f9c-4eab-971d-48abfda70a50; p=0cbee3304bce1ede82a56e901916d0949; first_login_flag=1; ln_hurl=http://hdn.xnimg.cn/photos/hdn421/20171230/1635/main_JQzq_ae7b0000a8791986.jpg; t=79bdd322e760beae79c0b511b8c92a6b9; societyguester=79bdd322e760beae79c0b511b8c92a6b9; id=327550029; xnsid=2ac9a5d8; loginfrom=syshome; ch_id=10016; wp_fold=0"    }    content = requests.get(url, headers=headers, timeout=3000)    # 设置编码格式    content.coding = 'UTF-8'    # 以文本形式获取源码    content_text = content.text    # 利用解析器进行解析操作    article = BeautifulSoup(content_text, "html.parser")    tag = article.find("iframe")    # 视频地址    video_page_url = tag.get("data-src")    # 参数获取 vid    params = parse.parse_qs(parse.urlparse(video_page_url).query)    vid = params['vid']    # 视频请求地址    video_request_url = "https://mp.weixin.qq.com/mp/videoplayer?action=get_mp_video_play_url&preview=0&__biz=&mid=&idx=&vid=%s&uin=&key=&pass_ticket=&wxtoken=&appmsg_token=&x5=0&f=json"    # 当前视频请求地址拼接    video_open_url = video_request_url % vid[0]    # 进行再次请求    header = {        "Accept": "*/*",        "Accept-Encoding": "gzip, deflate, br",        "Accept-Language": "zh-CN,zh;q=0.9",        "Connection": "keep-alive",        "Cookie": "rewardsn=; wxtokenkey=777; wxuin=1194235409; devicetype=Windows7; version=62080074; lang=zh_CN; pass_ticket=5P3kjZ6C4mxPyjk7V7PdoR0oth4Ngjp53kvkAEENdi8CV7JjoDaQHmYbnrzIzpwh; wap_sid2=CJGsurkEElwzY0tjSWV4U1hXdzRNazhkOXJ3SE8xZWVwNnBfaDZyM3NoZ3ZWRnpUaE5fOXlGYm01VVpKUmxKOW90ZlJzeHFQYTBWNGZrTy1nWHVkd3FiZVlEUXNzaFFFQUFBfjCz5JrxBTgNQAE=",        "Host": "mp.weixin.qq.com",        "Referer": video_page_url,        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36",        "X-Requested-With": "XMLHttpRequest"    }    response = requests.get(video_open_url, headers=header)    content = response.content.decode()    content = json.loads(content)    url_info = content.get("url_info")    # 视频标题    video_title = content.get("title")    # 视频地址    video_url2 = url_info[0].get("url")    # 开始下载视频    do_load_media(video_url2, "./file/%s.mp4" % video_title)# 下载视频def do_load_media(url, save_path):    try:        headers = {            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) '                          'Chrome/71.0.3578.98 Safari/537.36'}        pre_content_length = 0        # 循环接收视频数据        while True:            # 若文件已经存在，则断点续传，设置接收来需接收数据的位置            if os.path.exists(save_path):                headers['Range'] = 'bytes=%d-' % os.path.getsize(save_path)            res = requests.get(url, stream=True, headers=headers)            content_length = int(res.headers['content-length'])            # 若当前报文长度小于前次报文长度，或者已接收文件等于当前报文长度，则可以认为视频接收完成            if content_length < pre_content_length or (                    os.path.exists(save_path) and os.path.getsize(save_path) == content_length) or content_length == 0:                break            pre_content_length = content_length            # 写入收到的视频数据        
        with open(save_path, 'ab') as file:                file.write(res.content)           
         file.flush()                print('下载成功：文件大小 : %d  总下载大小:%d' % 
    
    
    (os.path.getsize(save_path), content_length))    except Exception as e:        
    print(e)if __name__ == '__main__':    print("微信公众号文章内视频下载~~~~~~~~")    path = main() 
       if not path:        
path = main()    # 解析链接    analysis(path)

